<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="addShow">添加分类</el-button>
        </el-col>
      </el-row>
      <tree-table class="treetable" :data="cateListData"
      :selection-type="false" :expand-type="false"
      show-index index-text="#"
      :columns="columns" stripe border>
        <template slot="icon" slot-scope="scope">
          <i class="el-icon-success" v-if="scope.row.cat_deleted === false" style="color: lightgreen"></i>
          <i class="el-icon-error" v-else style="color: red"></i>
        </template>
        <template slot="level" slot-scope="scope">
          <el-tag v-if="scope.row.cat_level === 0">一级</el-tag>
          <el-tag v-else-if="scope.row.cat_level === 1" type="success">二级</el-tag>
          <el-tag v-else type="warning">三级</el-tag>
        </template>
        <template slot="todo">
          <el-button type="primary" size="mini">编辑</el-button>
          <el-button type="danger" size="mini">删除</el-button>
        </template>
      </tree-table>
      <!-- 分页区域 -->
      <el-pagination
      @size-change="cateSizeChange"
      @current-change="cateCurrentChange"
      :current-page="queryInfo.pagenum"
      :page-sizes="[2, 5, 15, 20]"
      :page-size="queryInfo.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
      </el-pagination>
    </el-card>
    <!-- 添加分类对话框 -->
    <el-dialog
    title="添加分类"
    :visible.sync="addCateDialogVisible"
    width="50%" @closed="addCloseDialog">
      <!-- 添加分类表单 -->
      <el-form :model="addCateData" :rules="addCaterules"
      ref="addCateRef" label-width="100px"
      >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="addCateData.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类">
          <el-cascader :options="addListData" expand-trigger="hover"
          :props="addProps" v-model="selectedKeys"
          clearable change-on-select
          @change="parentCateChange">
          </el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addCateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCate">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 商品列表数据
      cateListData: [],
      // 添加分类表单级联选择器的数据
      addListData: [],
      // 请求参数
      queryInfo: {
        type: '',
        pagenum: '1',
        pagesize: '5'
      },
      // 商品列表总数据条数
      total: '',
      // 表格各列的配置
      columns: [
        {
          label: '分类名称',
          prop: 'cat_name'
        },
        {
          label: '是否有效',
          type: 'template',
          template: 'icon'
        },
        {
          label: '排序',
          type: 'template',
          template: 'level'
        },
        {
          label: '操作',
          type: 'template',
          template: 'todo',
          width: '200px'
        }
      ],
      // 控制添加分类对话框的显示与隐藏
      addCateDialogVisible: false,
      // 添加分类表单数据
      addCateData: {
        // 分类名称
        cat_name: '',
        // 父级分类id(被选中的最后一项)
        cat_pid: 0,
        // 分类的等级，默认为一级分类，值为0
        cat_level: 0
      },
      // 添加分类表单校验规则
      addCaterules: {
        cat_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ]
      },
      // 级联选择框的配置
      addProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // 被选中的父级分类的id数组
      selectedKeys: []
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get('categories', { params: this.queryInfo })
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品列表失败')
      }
      this.cateListData = res.data.result
      this.total = res.data.total
    },
    // 获取父级分类的数据列表
    async getParentCateList() {
      const { data: res } = await this.$http.get('categories', { params: { type: 2 } })
      if (res.meta.status !== 200) return this.$message.error('获取父级分类失败')
      this.addListData = res.data
    },
    // 监听分页区sizechange事件
    cateSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      this.getCateList()
    },
    // 监听分页区currentchange事件
    cateCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage
      this.getCateList()
    },
    // 监听添加分类按钮事件
    async addShow() {
      this.getParentCateList()
      this.addCateDialogVisible = true
    },
    // 监听级联选择框选项变化
    parentCateChange() {
      // 当选项发生变化时修改请求体也对应发生变化
      // 如果 selectedKeys 数组的长度大于0，证明选中了一级父级分类
      // 否则添加的分类就为一级分类
      if (this.selectedKeys.length > 0) {
        // 当前父级分类的id
        this.addCateData.cat_pid = this.selectedKeys[this.selectedKeys.length - 1]
        // 为当前添加的分类定义等级
        this.addCateData.cat_level = this.selectedKeys.length
      } else {
        this.addCateData.cat_pid = 0
        this.addCateData.act_level = 0
      }
    },
    addCate() {
      this.$refs.addCateRef.validate(async val => {
        if (!val) return
        const { data: res } = await this.$http.post('categories', this.addCateData)
        if (res.meta.status !== 201) return this.$message.info('添加分类失败')
        this.$message.success('添加分类成功')
        this.getCateList()
        this.addCateDialogVisible = false
      })
    },
    // 监听添加分类对话框关闭事件
    addCloseDialog() {
      this.$refs.addCateRef.resetFields()
      // 重置级联选择框的绑定的id数组
      this.selectedKeys = []
      // 重置父级分类id和当前分类等级
      this.addCateData.cat_pid = 0
      this.addCateData.act_level = 0
    }
  }
}
</script>

<style lang="less" scoped>
.treetable {
    margin-top: 20px;
}
.el-cascader {
  width: 100%
}
</style>
